<template>
  <el-dialog
    custom-class="add-user-comp"
    :title="title"
    :close-on-click-modal="false"
    :append-to-body="true"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(1200)"
    :before-close="handleCancel">
    <div class="form-container">
      <el-form
        :model="ruleForm"
        :rules="rules"
        size="medium"
        ref="ruleForm"
        class="rule-form"
      >
        <el-form-item class="custom-item-left" label="项目名称" prop="project_name" required>
          <el-input placeholder="请输入" v-model="ruleForm.project_name"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-right" label="是否重点项目" prop="is_project_important">
          <el-checkbox v-model="ruleForm.is_project_important"></el-checkbox>
        </el-form-item>
        <el-form-item class="custom-item-left" label="项目简称" prop="project_abbreviation">
          <el-input placeholder="请输入" v-model="ruleForm.project_abbreviation"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-right" label="所属单位" prop="project_company" required>
          <el-input placeholder="请输入" v-model="ruleForm.project_company"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left" label="状态" prop="project_status" required>
          <el-radio-group v-model="ruleForm.project_status">
            <el-radio label="在建工程"></el-radio>
            <el-radio label="竣工"></el-radio>
            <el-radio label="停工"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="custom-item-right" label="施工许可证编号" prop="construction_permit_id">
          <el-input placeholder="请输入" v-model="ruleForm.construction_permit_id"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left location" label="定位点" prop="point" required>
          <add-location v-model="ruleForm.point"></add-location>
        </el-form-item>
        <el-form-item class="custom-item-right" label="项目进度" prop="project_progres">
          <el-select placeholder="请选择项目进度" v-model="ruleForm.project_progres">
            <el-option label="基础阶段" value="基础阶段"></el-option>
            <el-option label="主体阶段" value="主体阶段"></el-option>
            <el-option label="装饰阶段" value="装饰阶段"></el-option>
            <el-option label="配套阶段" value="配套阶段"></el-option>
            <el-option label="竣工" value="竣工"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="custom-item-left" label="工程类别" prop="project_type" required>
          <el-select placeholder="请选择工程类别度" v-model="ruleForm.project_type">
            <el-option label="房建" value="房建"></el-option>
            <el-option label="市政" value="市政"></el-option>
            <el-option label="安装" value="安装"></el-option>
            <el-option label="装饰" value="装饰"></el-option>
            <el-option label="矿山" value="矿山"></el-option>
            <el-option label="公路" value="公路"></el-option>
            <el-option label="铁路" value="铁路"></el-option>
            <el-option label="水利水电" value="水利水电"></el-option>
            <el-option label="电力" value="电力"></el-option>
            <el-option label="化工石油" value="化工石油"></el-option>
            <el-option label="农林" value="农林"></el-option>
            <el-option label="港口与航道" value="港口与航道"></el-option>
            <el-option label="航天航空" value="航天航空"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="custom-item-right" label="工程用途" prop="project_purpose">
          <el-input placeholder="请输入" v-model="ruleForm.project_purpose"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left" label="结构类型" prop="building_structure" required>
          <el-select placeholder="请选择结构类型" v-model="ruleForm.building_structure">
            <el-option label="钢筋混凝土结构" value="钢筋混凝土结构"></el-option>
            <el-option label="框架结构" value="框架结构"></el-option>
            <el-option label="剪力墙结构" value="剪力墙结构"></el-option>
            <el-option label="框架-剪力墙结构" value="框架-剪力墙结构"></el-option>
            <el-option label="混合结构" value="混合结构"></el-option>
            <el-option label="筒体结构" value="筒体结构"></el-option>
            <el-option label="钢结构" value="钢结构"></el-option>
            <el-option label="型钢混凝土结构砖混结构" value="型钢混凝土结构砖混结构"></el-option>
            <el-option label="砖木结构" value="砖木结构"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="custom-item-right cost" label="工程造价" prop="project_cost">
          <el-input placeholder="请输入" v-model="ruleForm.project_cost"></el-input>万元
        </el-form-item>
        <el-form-item class="custom-item-left abbreviation" label="建筑面积" prop="area">
          <el-input placeholder="请输入" v-model="ruleForm.area"></el-input>平方米
        </el-form-item>
        <el-form-item class="custom-item-right" label="合同签订日期" prop="signing_date">
          <el-date-picker
            v-model="ruleForm.signing_date"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="custom-item-left period" label="合同工期" prop="contractDate">
          <el-date-picker
            v-model="ruleForm.contractDate"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="custom-item-left" label="开工日期" prop="commencement_date">
          <el-date-picker
            v-model="ruleForm.commencement_date"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="custom-item-right" label="竣工日期" prop="completion_date">
          <el-date-picker
            v-model="ruleForm.completion_date"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="custom-item-left address" label="项目地址" prop="project_address">
          <el-input placeholder="请输入项目地址" v-model="ruleForm.project_address"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left" label="标段编号" prop="section_id">
          <el-input placeholder="请输入" v-model="ruleForm.section_id"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-right" label="所属行政主管部门" prop="competent_administrative_department">
          <el-input placeholder="请输入" v-model="ruleForm.competent_administrative_department"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left" label="发薪日期" prop="payday">
          <el-date-picker
            v-model="ruleForm.payday"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="custom-item-right" label="行管部门行政区划" prop="divisions">
          <el-cascader
            placeholder="请选择行政区划"
            clearable
            filterable
            popper-class="address-popper"
            :props="{
              expandTrigger: 'click',
              value: 'name',
              label: 'name',
              children: 'children'
            }"
            v-model="ruleForm.divisions"
            :options="addressData"
            >
          </el-cascader>
        </el-form-item>
        <el-form-item class="custom-item-left" label="中标单位" prop="bidding_winner">
          <el-input placeholder="请输入" v-model="ruleForm.bidding_winner"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-right" label="设计单位" prop="designer" required>
          <el-input placeholder="请输入" v-model="ruleForm.designer"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left" label="建设单位" prop="constructorUnit" required>
          <el-input placeholder="请输入" v-model="ruleForm.constructorUnit"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-right" label="监理单位" prop="supervisor">
          <el-input placeholder="请输入" v-model="ruleForm.supervisor"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left" label="施工单位" prop="builder" required>
          <el-input placeholder="请输入" v-model="ruleForm.builder"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-right" label="勘察单位" prop="surveyor">
          <el-input placeholder="请输入" v-model="ruleForm.surveyor"></el-input>
        </el-form-item>
        <el-form-item class="custom-item-left survey" label="工地概况" prop="project_description">
          <el-input
            type="textarea"
            placeholder="请输入"
            :rows="2"
            v-model="ruleForm.project_description">
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button type="primary" @click="handleCancel">取 消</el-button>
      <el-button
        class="success"
        type="primary"
        :loading="loading"
        @click="hanldeSave">
        保 存
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addressData } from '@/utils/address';
import addLocation from '@/components/corp/addLocation';

export default {
  name: 'addProject',
  components: {
    addLocation
  },
  props: {
    // 弹框是否展示
    visible: {
      type: Boolean,
      default: true
    },
    // 表单编辑回填数据
    formData: {
      type: Object,
      default: () => ({})
    },
    // 新增、编辑
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      // 地址区划数据
      addressData,
      // form表单数据
      ruleForm: {
        // 项目名
        project_name: '',
        // 项目简称
        project_abbreviation: '',
        // 工程概况
        project_description: '',
        // 是否重点项目
        is_project_important: '',
        // 所属单位
        project_company: '',
        // 状态
        project_status: '',
        // 施工许可证编号
        construction_permit_id: '',
        // 项目进度
        project_progres: '',
        // 工程类别
        project_type: '',
        // 结构类型
        building_structure: '',
        // 工程用途
        project_purpose: '',
        // 工程造价，保留4位小数点
        project_cost: '',
        // 建筑面积，保留4位小数点
        area: '',
        // 合同签订时间
        signing_date: '',
        // 合同开始工期
        commencement_date: '',
        // 合同结束工期
        completion_date: '',
        // 合同工期
        contractDate: '',
        // 定位点
        point: {
          lng: '',
          lat: '',
          altitude: '',
        },
        // 项目地址
        project_address: '',
        // 标段编号
        section_id: '',
        // 所属行政主管部门
        competent_administrative_department: '',
        // 发薪日
        payday: '',
        // 中标单位
        bidding_winner: '',
        // 设计单位
        designer: '',
        // 建设单位
        constructorUnit: '',
        // 监理单位
        supervisor: '',
        // 施工单位
        builder: '',
        // 勘察单位
        surveyor: '',
        // 所属行政区划省
        divisions: []
      },
      // form 表单校验规则
      rules: {
        project_name: [
          { required: true, message: '请输入项目名称' }
        ],
        project_company: [
          { required: true, message: '请输入所属单位' }
        ],
        project_status: [
          { required: true, message: '请选择状态' }
        ],
        point: [
          { required: true, message: '请完善定位点信息' },
          { validator: this.pointValidator, trigger: 'blur' }
        ],
        project_type: [
          { required: true, message: '请选择工程类别', }
        ],
        building_structure: [
          { required: true, message: '请选择结构类型', }
        ],
        designer: [
          { required: true, message: '请输入设计单位' }
        ],
        builder: [
          { required: true, message: '请输入施工单位' }
        ],
        constructorUnit: [
          { required: true, message: '请输入建设单位' }
        ]
      },
      // 保存按钮loading
      loading: false
    };
  },
  computed: {
    // 设置弹框标题
    title() {
      return `${this.type === 'add' ? '新增' : '编辑'}项目`;
    }
  },
  watch: {
    // 监听回填数据
    formData: {
      deep: true,
      handler: function (data) {
        if (this.$checkType(data) === 'object') {
          const keys = Object.keys(this.ruleForm);
          keys.forEach(key => {
            let value = data[key];
            // 行政区划
            if (key === 'divisions') {
              const addressList = [
                data.administrative_divisions_province,
                data.administrative_divisions_city,
                data.administrative_divisions_county
              ];
              this.ruleForm[key] = addressList.filter(val => String(val));
              return;
            }
            // 建设单位
            if (key === 'constructorUnit') {
              value = data.constructor;
              this.ruleForm[key] = typeof value === 'function' ? '' : value;
              return;
            }
            // 定位点
            if (key === 'point') {
              this.ruleForm[key] = {
                lng: data.lng,
                lat: data.lat,
                altitude: data.altitude
              };
              return;
            }
            if (key === 'contractDate') {
              // contract_from: 合同开始工期 contract_to: 合同结束工期
              this.ruleForm[key] = [
                data.contract_from ? new Date(data.contract_from) : '',
                data.contract_to ? new Date(data.contract_to) : ''
              ].filter(val => val);
              return;
            }
            if (key === 'is_project_important') {
              this.ruleForm[key] = value === '是';
              return;
            }
            const hasval = ['undefined', 'null'].includes(this.$checkType(value));
            this.ruleForm[key] = hasval ? '' : value;
          });
        }
      }
    },
    // 监听弹框显示/隐藏
    visible(data) {
      if (!data) {
        Object.keys(this.ruleForm).forEach(key => {
          if (key === 'point') {
            this.ruleForm[key] = {
              lng: '',
              lat: '',
              altitude: ''
            };
            return;
          }
          if (key === 'divisions') {
            this.ruleForm[key] = [];
            return;
          }
          this.ruleForm[key] = '';
        });
        this.loading = false;
      }
    }
  },
  methods: {
    /**
     * 校验定位点信息
     * @param rule 校验规则
     * @param value 定位点数据
     * @param callback 校验回调
     */
    pointValidator(rule, value, callback) {
      const check = Object.keys(this.ruleForm.point).some(key => {
        return !value[key] || /^\s+$/.test(value[key]);
      });
      if (check) return callback('请完善定位点信息');
      return callback();
    },
    // 保存
    hanldeSave() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const datekeys = [
            'signing_date',
            'contractDate',
            'commencement_date',
            'completion_date',
            'payday'
          ];
          // 对时间字段调整格式重新赋值
          Object.keys(this.ruleForm).forEach(key => {
            const value = this.ruleForm[key];
            if (datekeys.includes(key) && value) {
              if (Array.isArray(value)) {
                this.ruleForm[key] = value.map(val => (
                  this.$moment(val).format('yyyy-MM-DD HH:mm:ss')
                ));
                return;
              }
              this.ruleForm[key] = this.$moment(value).format('yyyy-MM-DD HH:mm:ss');
            }
          });
          const {
            contractDate,
            point = {},
            project_cost,
            divisions,
            area,
            constructorUnit,
            is_project_important,
            ...others
          } = this.ruleForm;
          const options = {
            ...others,
            // lng: 经度, lat: 纬度, altitude: 海拔
            lng: point.lng ? parseFloat(point.lng).toFixed(6) : '',
            lat: point.lat ? parseFloat(point.lat).toFixed(6) : '',
            altitude: point.altitude ? parseFloat(point.altitude).toFixed(4) : '',
            // 建设单位
            constructor: constructorUnit,
            area: area ? parseFloat(area).toFixed(4) : '',
            // 工程造价，保留4位小数点
            project_cost: project_cost ? parseFloat(project_cost).toFixed(4) : '',
            // 合同开始工期，时间格式为yyyy-MM-dd hh:mm:ss
            contract_from: contractDate[0] || '',
            // 合同结束工期
            contract_to: contractDate[1] || '',
            is_project_important: is_project_important ? '是' : '否',
            // 所属行政区划
            administrative_divisions_province: divisions[0] || '',
            administrative_divisions_city: divisions[1] || '',
            administrative_divisions_county: divisions[2] || '',
          };
          if (this.type !== 'add') options.project_id = this.formData.project_id;
          this.$emit('submit', options);
          return;
        }
        this.$emit('submit', false);
      });
    },
    // 取消
    handleCancel() {
      this.$emit('cancel');
    }
  }
};
</script>

<style lang="scss" scoped>
  @import '../../assets/styles/dialog';
  .add-user-comp {
    .form-container {
      width: 100%;
      /deep/ .el-form {
        display: flex;
        flex-wrap: wrap;
        > div[class*="custom-item"] {
          width: 50%;
          float: left;
          display: flex;
          .el-form-item__label {
            color: #fff;
          }
          .el-form-item__content {
            width: 360px;
            .el-select, .el-cascader {
              width: 100%;
            }
            input {
              background-color: #0e0e2d;
              border: none;
              color: #fff;
            }
          }
          .el-radio {
            color: $mainColor;
            &.is-checked {
              .el-radio__label {
                color: #fff;
              }
            }
          }
          &.custom-item-left {
            .el-form-item__label {
              width: 120px;
            }
          }
          &.custom-item-right {
            .el-form-item__label {
              width: 200px;
            }
          }
          &.cost {
            .el-form-item__content {
              color: $mainColor;
              .el-input {
                width: 320px;
                margin-right: 5px;
              }
            }
          }
          &.abbreviation {
            .el-form-item__content {
              color: $mainColor;
              .el-input {
                width: 305px;
                margin-right: 5px;
              }
            }
          }
          &.period {
            width: 100%;
            .el-form-item__label {
              width: 120px;
            }
            .el-form-item__content {
              width: 600px;
              .el-date-editor {
                width: 100%;
                background-color: #0e0e2d;
                border: none;
                .el-range-separator {
                  color: $mainColor;
                }
              }
            }
          }
          &.address {
            width: 100%;
            .el-form-item__label {
              width: 120px;
            }
            .el-form-item__content {
              width: calc(100% - 140px);
            }
          }
          &.survey {
            width: 100%;
            .el-form-item__content {
              width: calc(100% - 140px);
              textarea {
                background-color: #0e0e2d;
                color: #fff;
                border: none;
              }
            }
          }
        }
      }
      /deep/ .el-form-item {
        margin-bottom: 15px;
      }
    }
    .dialog-footer {
      width: 100%;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .el-dialog__body {
      padding-top: 5px;
    }
  }
</style>
